package com.example.waitdemo.config;

import com.example.waitdemo.utils.HttpResult;
import com.example.waitdemo.utils.StringNullUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * @Description     StringNullRegex注解的实现
 * @ClassName StringNullRegexAspect
 * @Author jiang_11445266119198
 * @Date 2022/7/12 14:10
 */
@Aspect     // 切面
@Component  // 表示这是一个bean,由Spring进行管理 或者说输入spring
public class StringNullRegexAspect {

    // 配置织入点
    @Pointcut("@annotation(com.example.waitdemo.config.StringNullRegex)")
    public void annotationPointcut() {
    }

    @Around("annotationPointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Map<String, String> parameter = getParameter(method, joinPoint.getArgs());
        for (String key : parameter.keySet()) {
            //System.out.println("key= " + key + " and value= " + parameter.get(key));
            if (StringNullUtil.isEmpty(parameter.get(key))){
                return HttpResult.newError(key + "参数不能为空！");
            }
        }

        return joinPoint.proceed();
    }

    private Map<String, String> getParameter(Method method, Object[] args) {
        Map<String, String> argList = new  HashMap<>();
        Parameter[] parameters = method.getParameters();
        //System.out.println("parameters.length = " + parameters.length);
        for (int i = 0; i < parameters.length; i++) {
            //System.out.println("====================");
            //System.out.println("parameters[i] = " + parameters[i]);
            //System.out.println("parameters.getName() = " + parameters[i].getName());
            //System.out.println("args[i] = " + args[i]);
            //System.out.println("====================");
            argList.put(parameters[i].getName(), String.valueOf(args[i]));
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList;
        } else {
            return argList;
        }
    }
}